import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfo } from '@/api/api'
import { userApi } from '@/api/api'
import Cookies from 'js-cookie'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(Cookies.get('access_token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const isLogin = ref<boolean>(!!token.value)

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await userApi.getUserInfo()
      userInfo.value = res.data
      return res.data
    } catch (error) {
      console.error('获取用户信息失败：', error)
      return null
    }
  }

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const res = await userApi.login({ username, password })
      token.value = res.data.token
      Cookies.set('access_token', res.data.token, { expires: 7 }) // 设置7天过期
      isLogin.value = true
      return res.data
    } catch (error) {
      console.error('登录失败：', error)
      return null
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      await userApi.logout()
      token.value = ''
      userInfo.value = null
      isLogin.value = false
      Cookies.remove('access_token')
    } catch (error) {
      console.error('退出登录失败：', error)
    }
  }

  // 更新用户信息
  const updateUserInfo = async (data: Partial<UserInfo>) => {
    try {
      const res = await userApi.updateUserInfo(data)
      userInfo.value = res.data
      return res.data
    } catch (error) {
      console.error('更新用户信息失败：', error)
      return null
    }
  }

  return {
    token,
    userInfo,
    isLogin,
    getUserInfo,
    login,
    logout,
    updateUserInfo
  }
}) 